package com.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fh.common.util.Base64Util;
import com.fh.modules.ums.entity.UmsPartnerApply;
import com.fhMall.response.UmsMemberResponse;
import com.wechat.config.prperties.WxPayProperties;
import com.wechat.core.annotation.Token;
import com.wechat.core.bean.Result;
import com.wechat.feign.FhEmalMemberApi;
import com.wechat.models.request.LoginRequest;
import com.wechat.models.response.WxLoginResponse;
import com.wechat.service.user.WechatUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author
 * @date 2019-09-18 20:00:31
 */
@Controller
@RequestMapping("wechat/user")
@Api(tags = "")
public class WechatUserController extends BaseController{
    @Value("${wechat.share.baseUrl}")
    private String shareBaseUrl;
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private FhEmalMemberApi fhEmalMemberApi;

    @ApiOperation("查询我的积分历史")
    @GetMapping("/queryIntegrationChange")
    @ResponseBody
    public com.fh.common.api.vo.Result queryIntegrationChange(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        return fhEmalMemberApi.queryUsersIntegrationChange(this.getUserId(),pageNo,pageSize);
    }

    @ApiOperation(value = "登录")
    @GetMapping(value = "/login")
    @Token(required = false)
    @ResponseBody
    public Result<WxLoginResponse> weiXinAppletLogin(@RequestParam("openId") String openId,HttpServletResponse response) {
        LoginRequest loginRequest=new LoginRequest();
        loginRequest.setOpenid(openId);
        WxLoginResponse result = wechatUserService.wxLogin(loginRequest);
        Cookie cookie=new Cookie("token",result.getToken());
        cookie.setPath("/");
        cookie.setDomain(wxPayProperties.getDomain());
        response.addCookie(cookie);
        return new Result<WxLoginResponse>().result(result).msg("登录");
    }

    @GetMapping(value = "/access")
    @Token(required = false)
    @ResponseBody
    public String accessValidate(HttpServletRequest request){
        String echostr=request.getParameter("echostr");
        return echostr;
    }

    @ApiOperation("查询我的伙伴")
    @GetMapping("/queryBuddy")
    @ResponseBody
    public com.fh.common.api.vo.Result queryBuddy(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        return fhEmalMemberApi.queryBuddy(this.getUserId(),pageNo,pageSize);
    }

    @ApiOperation("用户基本信息")
    @GetMapping("/detail")
    @ResponseBody
    public JSONObject details() {
        return JSONObject.parseObject( fhEmalMemberApi.getMemberInfo(this.getUserId()));
    }

    @ApiOperation("用户是否关注公众号")
    @GetMapping("/focus")
    @ResponseBody
    public Result<WxMpUser> focusWp(){
        try{
            WxMpUser wxMpUser=wxMpService.getUserService().userInfo(this.getOpenId());
            System.out.println(JSONObject.toJSON(wxMpUser).toString());
            return new Result<>(wxMpUser);
        }catch (Exception e){
            e.printStackTrace();
        }
       return new Result<>();
    }

    @ApiOperation("修改")
    @PutMapping("/update")
    @ResponseBody
    public JSONObject update(@RequestBody UmsMemberResponse umsMemberResponse) {
        umsMemberResponse.setId(this.getUserId());
        String result = fhEmalMemberApi.putMember((JSONObject)JSONObject.toJSON(umsMemberResponse));
        return JSONObject.parseObject(result);
    }

    @ApiOperation("申请成为合伙人")
    @PostMapping("/apply")
    @ResponseBody
    public JSONObject apply(@RequestBody UmsPartnerApply umsPartnerApply) {
        umsPartnerApply.setMemberId(this.getUserId());
        String result = fhEmalMemberApi.apply(umsPartnerApply);
        return JSONObject.parseObject(result);
    }

    @ApiOperation("合伙人信息")
    @GetMapping("/parnterInfo")
    @ResponseBody
    public com.fh.common.api.vo.Result parnterInfo() {
        String shareUrl=shareBaseUrl  + "/" + this.getUserId()+"/"+ Base64Util.encodeData("http://"+wxPayProperties.getDomain());
        com.fh.common.api.vo.Result result=fhEmalMemberApi.getPartnerInfo(this.getUserId(),shareUrl);
        System.out.println(JSON.toJSON(result).toString());
        return result;
    }
    /**-------------模拟登陆用，后期删掉---------------------*/
    @GetMapping(value = "/wechatLogin")
    @Token(required = false)
    public String wechatLogin(@RequestParam("code") String code,
                              @RequestParam("state") String state,HttpServletResponse response,HttpServletRequest request){
        try {
            System.out.println(request.getSession().getId()+":注册-----------------------");
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            String openId = wxMpOAuth2AccessToken.getOpenId();
            LoginRequest loginRequest=new LoginRequest();
            loginRequest.setOpenid(openId);
            WxLoginResponse result=wechatUserService.wxLogin(loginRequest);
            Cookie cookie=new Cookie("token",result.getToken());
            cookie.setPath("/");
            cookie.setDomain(wxPayProperties.getDomain());
            response.addCookie(cookie);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "redirect:"+state;
    }

}
